<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>账单支付</title>
	<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>

<div id="root"></div>

<script>
	let search = location.search;
	const params = {}
	if (search && search.length) {
		search = search.slice(1);
		const searchs = search.split('&');
		searchs.forEach((str) => {
			const arr = str.split('=');
			params[arr[0]]=arr[1];
		});
		window.onload = function() {
			window.history.replaceState({}, 'temp', location.href.replace(location.search, ''));
			setTimeout(function(){
				wx.config({
					appId: params.appId, // 必填，公众号的唯一标识
					timestamp: params.timestamp, // 必填，生成签名的时间戳
					nonceStr: params.noncestr, // 必填，生成签名的随机串
					signature: params.signature,// 必填，签名
					jsApiList: [
						'onMenuShareTimeline',
						'onMenuShareAppMessage',
						'scanQRCode',
						'closeWindow',
						'addCard',
					] // 必填，需要使用的JS接口列表
				});
				wx.error((res) => {
					console.error(res);
				});
				wx.ready(ready);
			},500)
		}
	}
	function wxPay(data) {//调起微信支付方法
		return new Promise((callback, ret) => {
			window.WeixinJSBridge.invoke(
				'getBrandWCPayRequest', data,
				function(res) {
					if (res.err_msg === 'get_brand_wcpay_request:ok') callback(); // 支付成功
					else ret(res);
				}
			);
		});
	}
	function request(url,data){//简单封装请求方法
		return fetch(url,{
			method:'post',
			body: JSON.stringify({
				"appKey": "string",
				"data": data,
				"version": "string"
			}),
			headers: new Headers({
				'Content-Type': 'application/json',
				// 'Authorization': params.token
			})
		}).then(res=>res.json())
	}
	function ready(){
		request('/weixin/billPrePay',params.contractBillId).then(res => {//预支付
			if(res.code==='200'){
				console.log('预支付',res)
				wxPay(res.data).then(()=>{
					alert('支付成功。');
					window.wx.closeWindow();
				})
			}else{
				alert('预支付失败，请稍后重试。错误码（'+res.code+','+res.message+'）');
				window.wx.closeWindow();
			}
		})
	}
</script>

</body>
</html>
